{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f6e5420e",
   "metadata": {},
   "source": [
    "# week12 _字典的方法_字典的实践"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a09610ac",
   "metadata": {},
   "source": [
    "----\n",
    "* Author : liuqt\n",
    "* Time : 2021-11-15\n",
    "* week12\n",
    "* 学习线上资源:[Python官方文档](https://www.python.org/)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4162f996",
   "metadata": {},
   "source": [
    "### 本周知识点\n",
    "### 1.字典的一般方法\n",
    "\n",
    "> 1. 字典的查询  查询key -> value\n",
    ">> 1. 先看字典的key 是否存在 ： in 查询成员是否存在的重要方法\n",
    ">> 2. 查询\n",
    "> 2. 字典的修改\n",
    "> 3. 字典的删除\n",
    "> 4. 字典的增加 (dict_name[key] = value )\n",
    "\n",
    "### 2.字典的进阶方法\n",
    "\n",
    "> 1. 字典的初始化\n",
    ">> * D.fromkeys()\n",
    ">> * D.setdefault()\n",
    "\n",
    "### 3. 字典的实践（一）课本\n",
    "\n",
    "### 4. 字典的实践（二）课本\n",
    "\n",
    "### 5. 字典的实践（三）课外"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b7f7b09b",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "047176e2",
   "metadata": {},
   "source": [
    "### 1.字典的一般方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "83c91583",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'stu2001': 'xiaohong', 'stu2002': 'xiaoming', 'stu2003': 'xiaoli'}"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "stu_info = {\n",
    "    \"stu2001\":\"xiaohong\",\n",
    "    \"stu2002\":\"xiaoming\",\n",
    "    \"stu2003\":\"xiaoli\"\n",
    "}\n",
    "stu_info"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e627d44",
   "metadata": {},
   "source": [
    "> 1. 字典的查询\n",
    ">> 1. 直接查找 dict_name[key] 当关键词 key 不存在时，报错: KeyError: 'stu2004'\n",
    ">> 2. 使用 get 方法查找 当关键词 key 不存在时，返回 **None** 不存在。**不会报错**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "092ffdb4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'xiaohong'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 直接查找 dict_name[key]\n",
    "stu_info[\"stu2001\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "210e7d6c",
   "metadata": {},
   "outputs": [
    {
     "ename": "KeyError",
     "evalue": "'stu2004'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mKeyError\u001b[0m                                  Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-5-102cd6361404>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mstu_info\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m\"stu2004\"\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mKeyError\u001b[0m: 'stu2004'"
     ]
    }
   ],
   "source": [
    "stu_info[\"stu2004\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "79e2ab39",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on built-in function get:\n",
      "\n",
      "get(key, default=None, /) method of builtins.dict instance\n",
      "    Return the value for key if key is in the dictionary, else default.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# 使用 get 方法查找\n",
    "help(stu_info.get)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "12f1ddce",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'xiaohong'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "stu_info.get(\"stu2001\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "a4319567",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "None\n"
     ]
    }
   ],
   "source": [
    "print(stu_info.get(\"stu2004\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "277aa7c1",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "089fda2d",
   "metadata": {},
   "source": [
    "> 2. 修改 & 新增\n",
    ">> 1. 先查询 查看key是否存在 使用 in 查询成员\n",
    ">> 2. 如果 key 存在 修改 ： dict_name[key] = value\n",
    ">> 2. 如果 key **不存在** 新增：dict_name[key] = value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "1f0252c1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 查询 stu2004\n",
    "\"stu2004\" in stu_info"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "6bbc0c0b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 查询 stu2003\n",
    "\"stu2003\" in stu_info"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "068d5fe9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'stu2001': 'xiaohong', 'stu2002': 'xiaoming', 'stu2003': 'lihua'}"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 如果 key 存在 修改 \"stu2003\":\"xiaoli\" ---> \"stu2003\":\"lihua\"\n",
    "if \"stu2003\" in stu_info:\n",
    "    stu_info[\"stu2003\"] = \"lihua\"\n",
    "stu_info"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "77725aa6",
   "metadata": {},
   "source": [
    "> 3. 字典的删除\n",
    ">> 1. D.pop() 的一般操作如下：\n",
    ">>> 1. 先查询是否存在\n",
    ">>> 2. 在使用删除的方法\n",
    ">> 2. D.popitem()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "1ef50004",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on built-in function pop:\n",
      "\n",
      "pop(...) method of builtins.dict instance\n",
      "    D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n",
      "    If key is not found, d is returned if given, otherwise KeyError is raised\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(stu_info.pop)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "2c97aeea",
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "pop expected at least 1 argument, got 0",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-19-085d880744c3>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mstu_info\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mpop\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m: pop expected at least 1 argument, got 0"
     ]
    }
   ],
   "source": [
    "stu_info.pop()  # 不正确，不同于列表 （删除最后一个） "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "6549fc16",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'lihua'"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 字典删除的正确使用方法\n",
    "if \"stu2003\" in stu_info:\n",
    "    stu_info.pop(\"stu2003\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "542a6ba5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'stu2001': 'xiaohong', 'stu2002': 'xiaoming'}"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "stu_info"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "916fcdb0",
   "metadata": {},
   "outputs": [
    {
     "ename": "KeyError",
     "evalue": "'stu2004'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mKeyError\u001b[0m                                  Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-22-38b52b52774e>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mstu_info\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mpop\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"stu2004\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mKeyError\u001b[0m: 'stu2004'"
     ]
    }
   ],
   "source": [
    "# 如果不先查询 key 是否存在 ，有可能报错：KeyError: 'stu2004'\n",
    "stu_info.pop(\"stu2004\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "0d67ca06",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on built-in function popitem:\n",
      "\n",
      "popitem() method of builtins.dict instance\n",
      "    Remove and return a (key, value) pair as a 2-tuple.\n",
      "    \n",
      "    Pairs are returned in LIFO (last-in, first-out) order.\n",
      "    Raises KeyError if the dict is empty.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(stu_info.popitem)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "4a8cc18c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('stu2001', 'xiaohong')"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "stu_info.popitem()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "8fcee8a9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'stu2001': 'xiaohong', 'stu2002': 'xiaoming', 'stu2003': 'xiaoli'}"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "stu_info = {\n",
    "    \"stu2001\":\"xiaohong\",\n",
    "    \"stu2002\":\"xiaoming\",\n",
    "    \"stu2003\":\"xiaoli\"\n",
    "}\n",
    "stu_info"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "29ef5961",
   "metadata": {},
   "source": [
    "## 字典的实践（一）\n",
    "\n",
    "* 课本 P112\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "4002c1d3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provid a word to search for vowels: I love python\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'a': 0, 'e': 1, 'i': 0, 'o': 2, 'u': 0}"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 目标：查询 元音字母是否出现在 word 文本当中，并且统计出现的次数\n",
    "vowels = [\"a\",\"e\",\"i\",\"o\",\"u\"]\n",
    "word = input(\"Provid a word to search for vowels: \")\n",
    "found = {}\n",
    "\n",
    "# 字典 初始化 的值\n",
    "for i in vowels:\n",
    "    # 使用字典的新增 构建初始化字典\n",
    "    found [i] = 0\n",
    "    \n",
    "# 循环用户输入的文本，出现一次元音字符，对应的元音字符+1    \n",
    "for i in word:\n",
    "    if i in vowels:\n",
    "        found[i] +=1\n",
    "found"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3756ce99",
   "metadata": {},
   "source": [
    "> 字典的进阶方法：初始化所有值 fromkeys()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "a70eae0d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on built-in function fromkeys:\n",
      "\n",
      "fromkeys(iterable, value=None, /) method of builtins.type instance\n",
      "    Create a new dictionary with keys from iterable and values set to value.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(found.fromkeys)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "0d9ac878",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provid a word to search for vowels: this is\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'a': 0, 'e': 0, 'i': 2, 'o': 0, 'u': 0}"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "vowels = [\"a\",\"e\",\"i\",\"o\",\"u\"]\n",
    "word = input(\"Provid a word to search for vowels: \")\n",
    "found = {}\n",
    "\n",
    "# 初始化字典\n",
    "found = found.fromkeys(vowels,0)\n",
    "for i in word:\n",
    "    if i in vowels:\n",
    "        found[i] +=1\n",
    "found"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7d88a688",
   "metadata": {},
   "source": [
    "> 字典的进阶方法：初始化特定的值 setdefault()\n",
    "\n",
    ">> * 查询 key 是否出现在字典当中\n",
    ">>> 1. 出现过，就当没看见，不做任何操作\n",
    ">>> 2. key 未出现过，给定key及value(指定的初始化的值)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "8824f4eb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on built-in function setdefault:\n",
      "\n",
      "setdefault(key, default=None, /) method of builtins.dict instance\n",
      "    Insert key with a value of default if key is not in the dictionary.\n",
      "    \n",
      "    Return the value for key if key is in the dictionary, else default.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(found.setdefault)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "af29065b",
   "metadata": {},
   "outputs": [],
   "source": [
    "stu_password = {\n",
    "    \"xiaoming\" : \"222333\"\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "5a476359",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'123456'"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "stu_password.setdefault(\"lihua\",\"123456\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "d820770a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'xiaoming': '222333', 'lihua': '123456'}"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "stu_password"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "f86a83df",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'123456'"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "stu_password.setdefault(\"xiaohong\",\"123456\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "1f51bcc8",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'xiaoming': '222333', 'lihua': '123456', 'xiaohong': '123456'}"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "stu_password"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "86a420d1",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "e7f04ebc",
   "metadata": {},
   "source": [
    "## 字典的实践（二）\n",
    "\n",
    "* 课本 P121\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "6807beb3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provid a word to search for vowels: an apple\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'a': 2, 'e': 1}"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 优化：实践（二）\n",
    "\n",
    "vowels = [\"a\",\"e\",\"i\",\"o\",\"u\"]\n",
    "word = input(\"Provid a word to search for vowels: \")\n",
    "found = {}\n",
    "\n",
    "for i in word:\n",
    "    if i in vowels:\n",
    "        found.setdefault(i,0) # 特定情况下（字典中不存在该元素时，初始化其值）\n",
    "        found[i] +=1\n",
    "found\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9d6e94ea",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f8c78df6",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "70ab2fb8",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9d5d39c9",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
